from kivy.uix.layout import Layout
from kivy.properties import DictProperty


class BorderLayout(Layout):
    CENTER, SOUTH, NORTH, WEST, EAST = ('C', 'S', 'N', 'W', 'E')
    anchors = DictProperty()

    def __init__(self, **kwargs):
        super(BorderLayout, self).__init__(**kwargs)
        self.bind(
            anchors=self._trigger_layout,
            children=self._trigger_layout,
            orientation=self._trigger_layout,
            parent=self._trigger_layout,
            size=self._trigger_layout,
            pos=self._trigger_layout)

    @staticmethod
    def _get_side(widget):
        print widget, dir(widget)
        return getattr(widget, 'anchor', BorderLayout.CENTER)

    def do_layout(self, *largs):
        top = 0
        bottom = self.height
        left = 0
        right = self.width
        for w in self.children:
            if not w in self.anchors:
                self.anchors[w] = BorderLayout.CENTER
        max_height = 0
        for c, anchor in self.anchors.iteritems():
            if anchor == BorderLayout.SOUTH:
                c.x = left
                c.y = top
                c.height = min(c.height, bottom - top)
                c.width = right - left
                max_height = max(max_height, c.height)
        top += max_height

        max_height = 0
        for c, anchor in self.anchors.iteritems():
            if anchor == BorderLayout.NORTH:
                c.x = left
                c.y = bottom - c.height
                c.width = right - left
                c.height = min(c.height, bottom - top)
                max_height = max(max_height, c.height)
        bottom -= max_height

        max_width = 0
        for c, anchor in self.anchors.iteritems():
            if anchor == BorderLayout.EAST:
                c.x = right - c.width
                c.y = top
                c.height = bottom - top
                c.width = min(c.width, right - left)
                max_width = max(max_width, c.width)
        right -= max_width

        max_width = 0
        for c, anchor in self.anchors.iteritems():
            if anchor == BorderLayout.WEST:
                c.x = left
                c.y = top
                c.height = bottom - top
                c.width = min(c.width, right - left)
                max_width = max(max_width, c.width)
        left += max_width

        for c, anchor in self.anchors.iteritems():
            if anchor == BorderLayout.CENTER:
                c.x = left
                c.y = top
                c.height = bottom - top
                c.width = right - left

    def add_widget(self, widget, index=0):
        if not widget in self.anchors:
            self.anchors[widget] = BorderLayout.CENTER
        return super(BorderLayout, self).add_widget(widget, index)

    def remove_widget(self, widget):
        if widget in self.anchors:
            del self.anchors[widget]
        super(BorderLayout, self).remove_widget(widget)
